package com.heaboy.shiwu;

import java.sql.Connection;
import java.sql.DriverManager;

//jdbc事务管理器实现
public class JdbcTransactionManager implements TransactionManager{
    private Connection connection;
    private final String url;
    private final String password;
    private final String username;

    public JdbcTransactionManager(String url, String password, String username) {
        this.url = url;
        this.password = password;
        this.username = username;
    }

    @Override
    public void beginTransaction() throws Exception {
        if(connection==null|| connection.isClosed()){
            connection= DriverManager.getConnection(url,username,password);
        }
        connection.setAutoCommit(false);
    }

    @Override
    public void commit() throws Exception {
        if(connection!=null && !connection.isClosed()){
            connection.commit();
            connection.close();
        }
    }

    @Override
    public void rollback() throws Exception {
        if(connection!=null&&!connection.isClosed()){
            connection.rollback();
            connection.close();

        }
    }

    @Override
    public Connection getConnection() throws Exception {
        if(connection==null || connection.isClosed()){
            connection=DriverManager.getConnection(url,username,password);
        }
        return connection;
    }
}
